/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * @author yaoyuming
 * @date  2020-08-03 15:17
 */
package com.yao.mp;

import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.yao.core.Table;
import com.yao.util.FreemarkerUtil;

import java.util.List;
import java.util.Map;

/**
 * @author yaoyuming
 * @date 2020/08/03 15:17
 */
public class FreemarkerTemplateImpl extends FreemarkerTemplateEngine {

    public FreemarkerTemplateImpl() {
        super();
    }




    @Override
    public FreemarkerTemplateEngine init(ConfigBuilder configBuilder) {
        return super.init(configBuilder);
/*
        tables = configBuilder.getTableInfoList().stream().map(tableInfo -> {
            table = Table.db2Table(tableInfo);
            Map<String, String> cmap = table.getMap();
            configBuilder.getInjectionConfig().getMap().forEach((k,v) -> cmap.put(k, Objects.toString(v)));
            Console.log("cmap = {}",cmap);
            table.setMap(cmap);
            return table;
        }).collect(Collectors.toList());


        Console.log("tables = {}",tables);*/

    }

    @Override
    public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
//        super.writer(objectMap, templatePath, outputFile);



//        objectMap= BeanUtil.beanToMap(table);

//        TemplateUtil.createEngine(new TemplateConfig(Const.FTL_DIR, TemplateConfig.ResourceMode.CLASSPATH));

/*
        Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        configuration.setDefaultEncoding(ConstVal.UTF8);
        configuration.setClassForTemplateLoading(FreemarkerTemplateEngine.class, StringPool.SLASH);
        Template template = configuration.getTemplate(templatePath);
        try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
            template.process(objectMap, new OutputStreamWriter(fileOutputStream, ConstVal.UTF8));
        }
        logger.debug("模板:" + templatePath + ";  文件:" + outputFile);*/

/*
        TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("", TemplateConfig.ResourceMode.CLASSPATH));
        cn.hutool.extra.template.Template template1 = engine.getTemplate(templatePath);

        String render = template1.render(objectMap);
        FileUtil.appendUtf8String(render, outputFile);*/
//        FreemarkerUtil.createCode1(templatePath, outputFile, tables.get(0));

        /*Console.log("table = {}, templatePath = {}, outFile = {}",objectMap, templatePath, outputFile);*/
    }

    @Override
    public String templateFilePath(String filePath) {
        logger.info("模版：{}",filePath);
        return filePath;
    }



    @Override
    public AbstractTemplateEngine batchOutput() {
        try {
            List<TableInfo> tableInfoList = getConfigBuilder().getTableInfoList();

            tableInfoList.stream().forEach(tableInfo -> {

                // 生成代码
                FreemarkerUtil.generateCode(Table.db2Table(tableInfo));

                /*Table table = Table.db2Table(tableInfo);
                table.getMap().putAll(CustMapUtil.get());
                String module = table.getMap().get("module");
                String preTable = table.getMap().get("preTable");

                String className = StrUtil.upperFirst(module);
                FreemarkerUtil.createCode1("entity_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/entity/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("dto_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/entity/dto/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("mapper_sql_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/mapper/xml/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("mapper_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/mapper/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("service_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/service/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("service_impl_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/service/impl/" + className + "Entity.java", table);
                FreemarkerUtil.createCode1("controller_template.ftl", table.getMap().get("destPath") + "/temp/"+preTable+"/controller/" + className + "Entity.java", table);
*/

            });

            /*

            for (TableInfo tableInfo : tableInfoList) {
                Map<String, Object> objectMap = getObjectMap(tableInfo);
                Map<String, String> pathInfo = getConfigBuilder().getPathInfo();
                TemplateConfig template = getConfigBuilder().getTemplate();
                // 自定义内容
                InjectionConfig injectionConfig = getConfigBuilder().getInjectionConfig();
                if (null != injectionConfig) {
                    injectionConfig.initTableMap(tableInfo);
                    objectMap.put("cfg", injectionConfig.getMap());
                    List<FileOutConfig> focList = injectionConfig.getFileOutConfigList();
                    if (CollectionUtils.isNotEmpty(focList)) {
                        for (FileOutConfig foc : focList) {
                            if (isCreate(FileType.OTHER, foc.outputFile(tableInfo))) {
                                writer(objectMap, foc.getTemplatePath(), foc.outputFile(tableInfo));
                            }
                        }
                    }
                }

                // Mp.java
                String entityName = tableInfo.getEntityName();
                if (null != entityName && null != pathInfo.get(ConstVal.ENTITY_PATH)) {
                    String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + suffixJavaOrKt()), entityName);
                    logger.debug("输出文件:" + entityFile);
                    if (isCreate(FileType.ENTITY, entityFile)) {
                        table = Table.db2Table(tableInfo);
                        Map<String, String> cmap = table.getMap();
                        getConfigBuilder().getInjectionConfig().getMap().forEach((k,v) -> cmap.put(k, Objects.toString(v)));
                        table.setMap(cmap);
                        Console.log("table === {}",table);
                        FreemarkerUtil.createCode1(templateFilePath(template.getEntity(getConfigBuilder().getGlobalConfig().isKotlin())), entityFile, table);
                    }
                }
                // Dto.java
                if (null != entityName && null != pathInfo.get(ConstVal.ENTITY_PATH)) {
                    String entityFile = String.format((pathInfo.get(ConstVal.ENTITY_PATH) + File.separator + "%s" + suffixJavaOrKt()), entityName);
                    logger.debug("输出文件:" + entityFile);
                    if (isCreate(FileType.ENTITY, entityFile)) {

                        table = Table.db2Table(tableInfo);
                        Map<String, String> cmap = table.getMap();
                        getConfigBuilder().getInjectionConfig().getMap().forEach((k,v) -> cmap.put(k, Objects.toString(v)));
                        table.setMap(cmap);
                        Console.log("table === {}",table);
                        FreemarkerUtil.createCode1(templateFilePath(template.getEntity(getConfigBuilder().getGlobalConfig().isKotlin())), entityFile, table);
                    }
                }

                // MpMapper.java
                if (null != tableInfo.getMapperName() && null != pathInfo.get(ConstVal.MAPPER_PATH)) {
                    String mapperFile = String.format((pathInfo.get(ConstVal.MAPPER_PATH) + File.separator + tableInfo.getMapperName() + suffixJavaOrKt()), entityName);
                    if (isCreate(FileType.MAPPER, mapperFile)) {
                        writer(objectMap, templateFilePath(template.getMapper()), mapperFile);
                    }
                }
                // MpMapper.xml
                if (null != tableInfo.getXmlName() && null != pathInfo.get(ConstVal.XML_PATH)) {
                    String xmlFile = String.format((pathInfo.get(ConstVal.XML_PATH) + File.separator + tableInfo.getXmlName() + ConstVal.XML_SUFFIX), entityName);
                    if (isCreate(FileType.XML, xmlFile)) {
//                        writer(objectMap, templateFilePath(template.getXml()), xmlFile);
                    }
                }
                // IMpService.java
                if (null != tableInfo.getServiceName() && null != pathInfo.get(ConstVal.SERVICE_PATH)) {
                    String serviceFile = String.format((pathInfo.get(ConstVal.SERVICE_PATH) + File.separator + tableInfo.getServiceName() + suffixJavaOrKt()), entityName);
                    if (isCreate(FileType.SERVICE, serviceFile)) {
//                        writer(objectMap, templateFilePath(template.getService()), serviceFile);
                    }
                }
                // MpServiceImpl.java
                if (null != tableInfo.getServiceImplName() && null != pathInfo.get(ConstVal.SERVICE_IMPL_PATH)) {
                    String implFile = String.format((pathInfo.get(ConstVal.SERVICE_IMPL_PATH) + File.separator + tableInfo.getServiceImplName() + suffixJavaOrKt()), entityName);
                    if (isCreate(FileType.SERVICE_IMPL, implFile)) {
//                        writer(objectMap, templateFilePath(template.getServiceImpl()), implFile);
                    }
                }
                // MpController.java
                if (null != tableInfo.getControllerName() && null != pathInfo.get(ConstVal.CONTROLLER_PATH)) {
                    String controllerFile = String.format((pathInfo.get(ConstVal.CONTROLLER_PATH) + File.separator + tableInfo.getControllerName() + suffixJavaOrKt()), entityName);
                    if (isCreate(FileType.CONTROLLER, controllerFile)) {
//                        writer(objectMap, templateFilePath(template.getController()), controllerFile);
                    }
                }
            }*/
        } catch (Exception e) {
            logger.error("无法创建文件，请检查配置信息！", e);
        }
        return this;
    }

}